<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'controllers/admin.php';
require_once APPPATH . 'libraries/VideoEntry.php';

/**
 * Контроллер создания и изменения видео
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class Admin_Update_Video extends Admin {
   
   /**
    * Идентификатор видео
    *
    * @access private
    * @var integer
    */
   var $_id_video = 0;
   
   /**
    * Конструктор класса
    *
    * @access public
    * @return Admin_Update_Video
    */
   function Admin_Update_Video() {
      parent::Admin();
      // Выковыриваем идентификатор
      if (false !== $this->input->get('id')) {
         $this->_id_video = (int) $this->input->get('id');
      }
      $this->set_menu(6, 5);
      // Подгружаем модельку
      $this->load->model('m_video');
      $this->m_video->set_id($this->_id_video);
      $this->load->language('video');
      $this->load->model('m_table');
      $this->load->helper('element');
      $this->load->helper('text');
   } // end Admin_Update_Video
   
   /**
    * Метод по умолчанию
    *
    * @access public
    */
   function index() {
      $data = array();
      // Стандартные поля
      $title = $this->m_video->get('title');
      $orig_title = $this->m_video->get('orig_title');
      $image = $this->m_video->get('image');
      $year = $this->m_video->get('year');
      $length = $this->m_video->get('length');
      $description = $this->m_video->get('description');
      $trailer = $this->m_video->get('trailer');
      $genres = array();
      foreach ($this->m_video->get_genres() as $row) {
         array_push($genres, $row['id_genre']);
      }
      $countries = array();
      foreach ($this->m_video->get_countries() as $row) {
         array_push($countries, $row['id_country']);
      }
      $directors = array();
      foreach ($this->m_video->get_directors() as $row) {
         array_push($directors, $row['id_person']);
      }
      $actors = array();
      foreach ($this->m_video->get_actors() as $row) {
         array_push($actors, $row['id_person']);
      }
      
      // Валидируем и, если нужно, изменяем
      if (false !== $this->input->post('edit')) {
         $this->load->library('validation');
         $rules = array(
            'title'              => 'trim|required|max_length[200]',
            'orig_title'         => 'trim|max_length[200]',
            'year'               => 'trim|required|numeric',
            'length'             => 'trim',
            'description'        => 'trim',
            'directors'          => 'trim',
            'actors'             => 'trim',
            'trailer'            => 'trim'
         );
         $this->validation->set_rules($rules);
         $result = $this->validation->run();
         // Получаем из поста поля
         $title = $this->validation->title;
         if (isset($this->validation->orig_title)) {
            $orig_title = $this->validation->orig_title;
         } else {
            $orig_title = '';
         }
         if (isset($this->validation->year)) {
            $year = $this->validation->year;
         } else {
            $year = '';
         }
         if (isset($this->validation->length)) {
            $length = $this->validation->length;
         } else {
            $length = '';
         }
         if (isset($this->validation->description)) {
            $description = $this->validation->description;
         } else {
            $description = '';
         }
         if (isset($this->validation->trailer)) {
            $trailer = $this->validation->trailer;
         } else {
            $trailer = '';
         }
         // Получаем жанры
         if (is_array($this->input->post('genres'))) {
            $genres = $this->input->post('genres');
         } else {
            $genres = array();
         }
         // Получаем страны
         if (is_array($this->input->post('countries'))) {
            $countries = $this->input->post('countries');
         } else {
            $countries = array();
         }
         // Получаем режиссеров
         $directors = array();
         if (false !== $this->input->post('directors')) {
            $values = array_filter(explode('-', $this->input->post('directors')));
            if (!empty($values)) {
               $this->m_table->set_table('persons');
               $this->m_table->add_restriction('id_person', $values);
               foreach ($this->m_table->get_results() as $row) {
                  array_push($directors, $row['id_person']);
               }
            }
         }
         // Получаем актеров
         $actors = array();
         if (false !== $this->input->post('actors')) {
            $values = array_filter(explode('-', $this->input->post('actors')));
            if (!empty($values)) {
               $this->m_table->set_table('persons');
               $this->m_table->add_restriction('id_person', $values);
               foreach ($this->m_table->get_results() as $row) {
                  array_push($actors, $row['id_person']);
               }
            }
         }
         // Получаем изображение
         $config = array(
            'upload_path'   => $this->config->item('upload_path'),
            'allowed_types' => 'gif|jpg|png',
            'max_size'      => 1024,
            'encrypt_name'  => true
         );
         $this->load->library('upload', $config);
         if ($this->upload->do_upload('image')) {
            $image_data = $this->upload->data();
            // Перемещаем изображение в нужную папку
            $path = 'data/images/' . substr($image_data['file_name'], 0, 2) . '/';
            $full_path = BASEPATH . '../' . $path;
            if (!file_exists($full_path)) {
               mkdir($full_path, 0777, true);
            }
            if (copy($image_data['full_path'], $full_path . $image_data['file_name'])) {
               // Все удачно прошло
               $image = $path . $image_data['file_name'];
            } else {
               // Неудалось закачать файл
               $this->errors->set('image', $this->lang->line('upload_destination_error'));
               $result = false;
            }
            // Удаляем изображение из временной папки
            @unlink($image_data['full_path']);
         } else {
            if (!is_uploaded_file($_FILES['image']['tmp_name']) && '' != $this->input->post('hidden_image')) {
               $image = $this->input->post('hidden_image');
            } else {
               $image = '';
            }
         }
         
         if ($result) {
            // Если проверки пройдены успешно, изменяем стиль
            if (0 == $this->_id_video) {
               $this->m_video->set('status', 'active');
               $this->m_video->set('date_created', mdate('%Y-%m-%d %H:%i:%s'));
            }
            $this->m_video->set('title', $title);
            $this->m_video->set('orig_title', $orig_title);
            $this->m_video->set('image', $image);
            $this->m_video->set('year', $year);
            $this->m_video->set('length', $length);
            $this->m_video->set('description', $description);
            $this->m_video->set('trailer', $trailer);
            $entry = new VideoEntry();
            $entry->setTitle($title);
            $entry->setOrigTitle($orig_title);
            $titlehash = $entry->getTitleHash();
            $this->m_video->set('titlehash', $titlehash);
            // Сохраняем в базу
            if ($this->m_video->update()) {
               // Устанавливаем режиссеров
               $this->m_video->set_directors($directors);
               // Устанавливаем актеров
               $this->m_video->set_actors($actors);
               // Устанавливаем жанры
               $this->m_video->set_genres($genres);
               // Устанавливаем страны
               $this->m_video->set_countries($countries);
               
               if (0 == $this->_id_video) {
                  $this->set_message($this->lang->line('add_video_succ'), 'info', true);
                  $this->redirect('admin_manage_torrents', 'index', array('video' => $this->m_video->get_id('id_video')));
               } else {
                  $this->set_message($this->lang->line('edit_video_succ'), 'info', true);
                  $this->redirect('admin_manage_videos');
               }
            }
            // Если сюда пришли, значит не все в порядке...
            if (0 == $this->_id_video) {
               $this->set_message($this->lang->line('add_video_error'), 'error');
            } else {
               $this->set_message($this->lang->line('edit_video_error'), 'error');
            }
         }
      }
      
      // Обрабатываем список жанров
      $this->m_table->set_table('genres');
      $this->m_table->add_sort('title');
      $objects = $this->m_table->get_results();
      foreach ($objects as $id => $object) {
         $object['checkbox'] = create_checkbox('genres[]', in_array($object['id_genre'], $genres), 'value="' . $object['id_genre'] . '"');
         $object['checked'] = in_array($object['id_genre'], $genres);
         $objects[$id] = $object;
      }
      usort($objects, array($this, '_sort_objects'));
      $data['genres'] = $objects;
            
      // Обрабатываем список стран
      $this->m_table->set_table('countries');
      $this->m_table->add_sort('title');
      $objects = $this->m_table->get_results();
      foreach ($objects as $id => $object) {
         $object['checkbox'] = create_checkbox('countries[]', in_array($object['id_country'], $countries), 'value="' . $object['id_country'] . '"');
         $object['checked'] = in_array($object['id_country'], $countries);
         $objects[$id] = $object;
      }
      usort($objects, array($this, '_sort_objects'));
      $data['countries'] = $objects;
            
      // Обрабатываем список режиссеров
      $b_directors = array();
      if (0 < count($directors)) {
         $this->m_table->set_table('persons');
         $this->m_table->add_restriction('id_person', $directors);
         foreach ($this->m_table->get_results() as $director) {
            $value = array(
               'id'    => $director['id_person'],
               'title' => $director['title']
            );
            array_push($b_directors, $value);
         }
      }
      $data['directors'] = json_encode($b_directors);
      
      // Обрабатываем список актеров
      $b_actors = array();
      if (0 < count($actors)) {
         $this->m_table->set_table('persons');
         $this->m_table->add_restriction('id_person', $actors);
         foreach ($this->m_table->get_results() as $actor) {
            $value = array(
               'id'    => $actor['id_person'],
               'title' => $actor['title']
            );
            array_push($b_actors, $value);
         }
      }
      $data['actors'] = json_encode($b_actors);
      
      // Забиваем в дату поля
      $data['id'] = $this->_id_video;
      $data['title'] = htmlspecialchars($title);
      $data['orig_title'] = htmlspecialchars($orig_title);
      $data['year'] = 0 < $year ? $year : '';
      $data['length'] = $length;
      $data['description'] = $description;
      $data['trailer'] = $trailer;
      $data['image'] = $image;
      $data['image_exists'] = empty($image) ? array() : array(array());
      
      // Выводим
      $view = 'admin/edit_video.html';
      if (0 == $this->_id_video) {
         $view = 'admin/add_video.html';
      }
      $this->set_content($this->parser->parse($view, $data, true));
      $this->display();
   } // end index
   
   /**
    * Сортировка объектов
    *
    * @param array $a
    * @param array $b
    * @return bool
    */
   function _sort_objects($a, $b) {
      if ($a['checked'] < $b['checked']) {
          return 1;
      } elseif ($a['checked'] > $b['checked']) {
          return -1;
      } else {
          return strcmp(mb_strtolower($a['title'], 'UTF-8'), mb_strtolower($b['title'], 'UTF-8'));
      }
      return 0;
   }
   
}
